package com.ljy.jymail.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

//登录逻辑
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /*
    * @TODO 根据token获取用户信息
    * @author ljy
    * @time 2022-01-28 03:15:41
    * @method userInfo
    * @param param
    * @return java.lang.String
    */
    @ResponseBody
    @GetMapping("userInfo")
    public String userInfo(@RequestParam("token") String token){
        return stringRedisTemplate.opsForValue().get(token);
    }

    /*
    * @TODO 单点登录服务端登录逻辑
    * @author ljy
    * @time 2022-01-28 03:34:28
    * @method doLogin
    * @param param
    * @return java.lang.String
    */
    @PostMapping("/dologin")
    public String doLogin(@RequestParam("url") String url,
                          HttpServletResponse response,
                          @RequestParam("password")String password,
                          @RequestParam("username")String username){
        if (!StringUtils.isEmpty(password)&&!StringUtils.isEmpty(username)){
            //登陆成功
            //将登陆成功的信息保存到redis,生成独一无二的key供客户端使用
            //如UUID()，雪花算法,数据库自增id
            String uuid = UUID.randomUUID().toString().replace("-","");
            stringRedisTemplate.opsForValue().set(uuid,username);

            //留下用户登陆的痕迹-cookie
            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);
            return "redirect:"+url+"?"+"token="+uuid;
        }
        //登陆失败跳转,跳回登录页
        System.out.println("--------"+url);
        return "login";
    }

    /*
    * @TODO 单点登录时判断是否登陆过
    * @author ljy
    * @time 2022-01-28 03:59:27
    * @method loginPage
    * @param param
    * @return java.lang.String
    */
    @GetMapping("/login.html")
    public String loginPage(
            @RequestParam("redirect_url") String url,
            Model model,
            @CookieValue(value = "sso_token",required = false)String token){
        //如果能获取到cookie的值，说明之前有人登陆过，直接返回方法
        if (!StringUtils.isEmpty(token)){
            return "redirect:"+url+"?token="+token;
        }
        model.addAttribute("url",url);
        //跳转登录页
        return "login";
    }


}
